// OCRResultScreen.kt
package com.example.nutritionmanager.ocr

import android.annotation.SuppressLint
import android.app.Activity
import android.net.Uri
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.nutritionmanager.AIChatCard
import com.example.nutritionmanager.bodys.responseBodys.OCRResultItem
import com.example.nutritionmanager.home.getCurrentDate
import com.example.nutritionmanager.record.getCurrentMealType
import com.example.nutritionmanager.viewModels.AIPromptState
import com.example.nutritionmanager.viewModels.AIPromptViewModel
import com.example.nutritionmanager.viewModels.NutritionState
import com.example.nutritionmanager.viewModels.NutritionViewModel
import com.example.nutritionmanager.viewModels.ResultState
import com.example.nutritionmanager.viewModels.ResultViewModel

@SuppressLint("StateFlowValueCalledInComposition")
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun OCRResultScreen(
    nutritionViewModel: NutritionViewModel = hiltViewModel(),
    resultViewModel: ResultViewModel = hiltViewModel(),
    aiViewModel: AIPromptViewModel = hiltViewModel(),
    uri: Uri
) {
    val colorScheme = MaterialTheme.colorScheme
    // ViewModel 状态收集
    val nutritionState by nutritionViewModel.nutritionState.collectAsState()
    val selectedResults by resultViewModel.selectedResults.collectAsState()
    val selectedNutritions by nutritionViewModel.selectedNutritions.collectAsState()
    val nutritionInputs by nutritionViewModel.nutritionInputs.collectAsState()
    val selectedResultInputs by resultViewModel.selectedResultInputs.collectAsState()
    val resultState by resultViewModel.resultState.collectAsState()
    val aiPromptState by aiViewModel.aiPromptState.collectAsState()
    val foodWeightInput by resultViewModel.foodWeightInput.collectAsState()
    val foodWeight by resultViewModel.foodWeight.collectAsState()

    // UI 状态和控制
    val snackbarHostState = remember { SnackbarHostState() }
    val scope = rememberCoroutineScope()
    val focusManager = LocalFocusManager.current
    val keyboardController = LocalSoftwareKeyboardController.current

    val context = LocalContext.current
    val activity = remember { context as? Activity }

    // 下拉菜单的展开状态
    var dropdownExpanded by remember { mutableStateOf(false) }

    // 新增ai对话状态控制
    var aiPromptMessage by remember { mutableStateOf<String?>(null) }

    // 获取 OCR 结果，当界面首次显示时调用 fetchResult()
    LaunchedEffect(Unit) {
        resultViewModel.uploadImage(context, uri)
    }
    // 监听状态变化以显示 Snackbar 和进行导航
    LaunchedEffect(resultState) {
        when (resultState) {
            is ResultState.SaveSuccess -> {
                val message = (resultState as ResultState.SaveSuccess).message
                snackbarHostState.showSnackbar(message)
            }
            is ResultState.SaveError -> {
                val errorMessage = (resultState as ResultState.SaveError).error
                snackbarHostState.showSnackbar(errorMessage)
                resultViewModel.resetState()
            }
            is ResultState.Error -> {
                val errorMessage = (resultState as ResultState.Error).error
                snackbarHostState.showSnackbar(errorMessage)
                resultViewModel.resetState()
            }
            else -> {}
        }
    }
    // 计算下拉菜单中可用的营养成分
    val availableNutritions = when (nutritionState) {
        is NutritionState.Success -> {
            val allNutritions = (nutritionState as NutritionState.Success).nutritions
            allNutritions.filter { nutrition ->
                !selectedNutritions.any { it.nutritionId == nutrition.nutritionId }
            }
        }
        else -> emptyList()
    }

    val availableResults = when (resultState) {
        is ResultState.Success -> {
            val allResults = (resultState as ResultState.Success).ocrResult
            allResults.results.filter { result ->
                !selectedResults.any { it.nutritionId == result.nutritionId }
            }
        }
        else -> emptyList()
    }

    // 表单验证，确保所有选定的营养成分都有有效的输入
    val isFormValid = selectedNutritions.isNotEmpty() && selectedNutritions.all { nutrition ->
        val value = nutritionInputs[nutrition.nutritionId]
        value?.isNotBlank() == true && value.toDoubleOrNull() != null
    }

    Scaffold(
        snackbarHost = { SnackbarHost(hostState = snackbarHostState) },
        topBar = {
            TopAppBar(
                title = { Text("识别结果", color = colorScheme.onPrimary) },
                navigationIcon = {
                    IconButton(onClick = { activity?.finish() }) {
                        Icon(
                            imageVector = Icons.Filled.ArrowBack,
                            contentDescription = "返回",
                            tint = colorScheme.onPrimary // 将箭头颜色设置为白色
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primary
                )
            )
        }
    ) { paddingValues ->
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(top = 5.dp, bottom = 16.dp)
        ) {
            when (resultState) {
                is ResultState.Loading -> {
                    // 显示加载状态
                    Column(
                        modifier = Modifier
                            .fillMaxSize()
                            .background(Color.White.copy(alpha = 0.9f)),
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.Center
                    ) {
                        CircularProgressIndicator(
                            modifier = Modifier.size(48.dp),
                            color = MaterialTheme.colorScheme.primary
                        )
                        Spacer(modifier = Modifier.height(16.dp))
                        Text(
                            text = "正在识别中...",
                            color = MaterialTheme.colorScheme.primary,
                            fontSize = 16.sp
                        )
                    }
                }
                else -> {
                    Column(
                        modifier = Modifier
                            .fillMaxSize()
                            .verticalScroll(rememberScrollState()) // 使页面可垂直滑动
                            .background(colorScheme.background)
                            .padding(paddingValues)
                            .padding(16.dp),
                        verticalArrangement = Arrangement.Top
                    ) {
                        // 食物重量输入
                        Card(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(bottom = 16.dp),
                            colors = CardDefaults.cardColors(containerColor = colorScheme.surface),
                            shape = MaterialTheme.shapes.medium
                        ) {
                            Column(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(16.dp)
                            ) {
                                Text(
                                    text = "食用重量",
                                    fontSize = 16.sp,
                                    color = colorScheme.onSurface,
                                    style = MaterialTheme.typography.titleMedium
                                )
                                Spacer(modifier = Modifier.height(8.dp))
                                Row(
                                    verticalAlignment = Alignment.CenterVertically,
                                    modifier = Modifier.fillMaxWidth()
                                ) {
                                    Box(
                                        modifier = Modifier
                                            .weight(1f)
                                            .height(40.dp)
                                            .background(
                                                color = colorScheme.surfaceVariant,
                                                shape = RoundedCornerShape(4.dp)
                                            ),
                                        contentAlignment = Alignment.Center
                                    ) {
                                        BasicTextField(
                                            value = foodWeightInput.toString(),
                                            onValueChange = { newValue ->
                                                val trimmed = newValue.trim()
                                                when {
                                                    trimmed.isEmpty() -> {
                                                        // 自动填入 0
                                                        resultViewModel.updateFoodWeightInput("0")
                                                    }
                                                    trimmed.toIntOrNull() != null && trimmed.toInt() >= 0 -> {
                                                        resultViewModel.updateFoodWeightInput(trimmed)
                                                    }
                                                    // 其他非法输入不处理（保留原值）
                                                }
                                            },
                                            singleLine = true,
                                            textStyle = TextStyle(
                                                fontSize = 16.sp,
                                                color = colorScheme.onSurface
                                            ),
                                            keyboardOptions = KeyboardOptions.Default.copy(
                                                keyboardType = KeyboardType.Number,
                                                imeAction = ImeAction.Done
                                            ),
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .padding(horizontal = 12.dp)
                                        )
                                    }
                                    Spacer(modifier = Modifier.width(8.dp))
                                    Text(
                                        text = "克",
                                        fontSize = 16.sp,
                                        color = colorScheme.onSurface
                                    )
                                }
                            }
                        }

                        // 营养成分表标题
                        Text(
                            text = "营养成分表 (每${foodWeight}克)",
                            fontSize = 18.sp,
                            color = colorScheme.onBackground,
                            style = MaterialTheme.typography.titleMedium,
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(bottom = 16.dp),
                        )

                        // 显示已选的营养成分列表，并在每项之间添加分割线
                        Card(
                            modifier = Modifier
                                .fillMaxWidth(),
                            colors = CardDefaults.cardColors(containerColor = colorScheme.surface),
                            shape = MaterialTheme.shapes.medium
                        ) {
                            Column(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(16.dp)
                            ) {
                                Text(
                                    text = "每份重量",
                                    fontSize = 14.sp,
                                    color = colorScheme.onSurface,
                                    style = MaterialTheme.typography.titleMedium
                                )
                                Spacer(modifier = Modifier.height(8.dp))
                                Row(
                                    verticalAlignment = Alignment.CenterVertically,
                                    modifier = Modifier.fillMaxWidth()
                                ) {
                                    Box(
                                        modifier = Modifier
                                            .weight(1f)
                                            .height(40.dp)
                                            .background(
                                                color = colorScheme.surfaceVariant,
                                                shape = RoundedCornerShape(4.dp)
                                            ),
                                        contentAlignment = Alignment.Center
                                    ) {
                                        BasicTextField(
                                            value = foodWeight.toString(),
                                            onValueChange = { newValue ->
                                                val trimmed = newValue.trim()
                                                when {
                                                    trimmed.isEmpty() -> {
                                                        // 自动填入 0
                                                        resultViewModel.updateFoodWeight("0")
                                                    }
                                                    trimmed.toIntOrNull() != null && trimmed.toInt() >= 0 -> {
                                                        resultViewModel.updateFoodWeight(trimmed)
                                                    }
                                                    // 其他非法输入不处理（保留原值）
                                                }
                                            },
                                            singleLine = true,
                                            textStyle = TextStyle(
                                                fontSize = 16.sp,
                                                color = colorScheme.onSurface
                                            ),
                                            keyboardOptions = KeyboardOptions.Default.copy(
                                                keyboardType = KeyboardType.Number,
                                                imeAction = ImeAction.Done
                                            ),
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .padding(horizontal = 12.dp)
                                        )
                                    }
                                    Spacer(modifier = Modifier.width(8.dp))
                                    Text(
                                        text = "克",
                                        fontSize = 14.sp,
                                        color = colorScheme.onSurface
                                    )
                                }
                            }
                            Column {
                                selectedResults.forEachIndexed { index, resultItem ->
                                    val inputValue =
                                        selectedResultInputs[resultItem.nutritionId]?.let { it } ?: ""
                                    ResultItemUI(
                                        ocrResultItem = resultItem,
                                        inputValue = inputValue,
                                        onValueChange = { value ->
                                            resultViewModel.updateRecordAmount(resultItem.nutritionId, value)
                                        },
                                        onRemove = {
                                            resultViewModel.removeSelectedResult(resultItem)
                                        }
                                    )
                                    // 在每项之间添加 Divider，除了最后一项
                                    if (index < selectedResults.size - 1) {
                                        Spacer(
                                            modifier = Modifier.fillMaxWidth().padding(horizontal = 10.dp)
                                                .height(1.dp).border(1.dp, colorScheme.surfaceVariant)
                                        )
                                    } else {
                                        Spacer(modifier = Modifier.height(8.dp))
                                    }
                                }
                                Row (
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(horizontal = 8.dp),
                                    horizontalArrangement = Arrangement.SpaceBetween
                                ){
                                    OutlinedButton(
                                        onClick = { dropdownExpanded = true },
                                        modifier = Modifier.weight(2f)
                                            .fillMaxWidth()
                                            .padding(14.dp),
                                        colors = ButtonDefaults.outlinedButtonColors(
                                            containerColor = colorScheme.surface
                                        )
                                    ) {
                                        Icon(
                                            imageVector = Icons.Default.Add,
                                            contentDescription = "添加",
                                            tint = colorScheme.onSurface,
                                            modifier = Modifier.size(20.dp)
                                        )
                                        Spacer(modifier = Modifier.width(4.dp))
                                        Text(text = "添加营养成分", color = colorScheme.onSurface)
                                    }
                                    // 问问AI按钮
                                    Button(
                                        onClick = {
                                            // 构建营养数据消息
                                            val nutritionData = selectedResults.joinToString(", ") {
                                                "${it.nutritionName}: ${selectedResultInputs[it.nutritionId]}${it.unit}"
                                            }
                                            when(aiPromptState){
                                                AIPromptState.Idle -> {}
                                                AIPromptState.Loading -> {}
                                                is AIPromptState.Success -> {
                                                    aiPromptMessage = (aiPromptState as AIPromptState.Success).prompt + "当前摄入食物营养数据：$nutritionData"
                                                }
                                                is AIPromptState.Error -> {}
                                            }
                                        },
                                        colors = ButtonDefaults.buttonColors(
                                            containerColor = MaterialTheme.colorScheme.primary
                                        ),
                                        modifier = Modifier
                                            .weight(1f)
                                            .padding(vertical = 14.dp)
                                            .padding(end = 10.dp)
                                    ) {
                                        Text(text = "问问AI", color = colorScheme.onPrimary)
                                    }
                                }


                                DropdownMenu(
                                    expanded = dropdownExpanded,
                                    onDismissRequest = { dropdownExpanded = false },
                                    modifier = Modifier
                                        .widthIn(max = 250.dp)
                                        .background(colorScheme.surface)
                                ) {
                                    availableNutritions.forEach { nutrition ->
                                        DropdownMenuItem(
                                            text = { Text(text = nutrition.nutritionName, color = colorScheme.onSurface) },
                                            onClick = {
                                                resultViewModel.addSelectedResult(nutrition)
                                                dropdownExpanded = false
                                            }
                                        )
                                    }
                                    if (availableNutritions.isEmpty()) {
                                        DropdownMenuItem(
                                            text = { Text(text = "没有更多营养成分") },
                                            onClick = { /* 不做任何操作 */ },
                                            enabled = false
                                        )
                                    }
                                }
                            }
                        }
                        Spacer(modifier = Modifier.height(24.dp))
                        // AI对话标题
                        Text(
                            text = "AI建议",
                            fontSize = 18.sp,
                            color = Color.Black,
                            style = MaterialTheme.typography.titleMedium,
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(bottom = 16.dp),
                        )
                        // AI 对话卡片
                        AIChatCard(
                            externalMessage = aiPromptMessage,
                            onExternalMessageProcessed = { aiPromptMessage = null })
                        Spacer(modifier = Modifier.height(24.dp))

                        // 按钮区
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(horizontal = 8.dp),
                            horizontalArrangement = Arrangement.SpaceBetween
                        ) {
                            // 忍住不吃按钮
                            Button(
                                onClick = {
                                    activity?.finish()
                                },
                                colors = ButtonDefaults.buttonColors(
                                    containerColor = Color.LightGray
                                ),
                                modifier = Modifier
                                    .weight(1f)
                                    .padding(end = 4.dp)
                            ) {
                                Text(text = "忍住不吃", color = Color.Black)
                            }

                            // 记录此食物按钮
                            Button(
                                onClick = {
//                                if (isFormValid) {
//                                    resultViewModel.saveNutritionRecord(getCurrentDate(), getCurrentMealType())
//                                    activity?.finish()
//                                } else {
//                                    scope.launch {
//                                        snackbarHostState.showSnackbar("请填写所有必填项且确保输入有效")
//                                    }
//                                }
                                    resultViewModel.saveNutritionRecord(getCurrentDate(), getCurrentMealType())

                                },
                                colors = ButtonDefaults.buttonColors(
                                    containerColor = MaterialTheme.colorScheme.primary
                                ),
                                modifier = Modifier
                                    .weight(1f)
                                    .padding(start = 4.dp)
                            ) {
                                Text(text = "记录此食物", color = Color.White)
                            }
                        }
                    }
                }
            }
        }
    }

    // 处理 ResultViewModel 的状态变化（例如显示错误信息）
    LaunchedEffect(resultState) {
        when (resultState) {
            is ResultState.Error -> {
                snackbarHostState.showSnackbar((resultState as ResultState.Error).error)
                resultViewModel.resetState()
            }
            else -> {}
        }
    }
}

@Composable
fun ResultItemUI(
    ocrResultItem: OCRResultItem,
    inputValue: String,
    onValueChange: (String) -> Unit,
    onRemove: () -> Unit
) {
    val colorScheme = MaterialTheme.colorScheme
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .background(colorScheme.surface)
            .padding(4.dp) // 减少内层内边距
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier.fillMaxWidth()
        ) {
            Text(
                text = "${ocrResultItem.nutritionName} (${ocrResultItem.unit})",
                fontSize = 14.sp, // 可选：减小字体大小
                color = colorScheme.onSurface,
                modifier = Modifier
                    .weight(1f)
                    .padding(start = 8.dp)
            )
            if (!ocrResultItem.isMatched && ocrResultItem.ocrName != null) {
                Text(
                    text = "原始识别结果为${ocrResultItem.ocrName}，AI已为您分类到更常规的成分。",
                    color = Color.Red,
                    fontSize = 12.sp,
                    modifier = Modifier
                        .weight(1f)
                        .padding(end = 8.dp)
                )
            }
            IconButton(onClick = { onRemove() }) {
                Icon(
                    modifier = Modifier.size(16.dp),
                    imageVector = Icons.Default.Delete,
                    contentDescription = "移除",
                    tint = Color.Gray
                )
            }
        }
        // 输入框部分
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 12.dp) // 增加输入框与父容器左右边框的间距
                .height(40.dp)
                .background(color = colorScheme.surfaceVariant, shape = RoundedCornerShape(4.dp)),
            contentAlignment = Alignment.Center // 内容在Box中居中
        ) {
            BasicTextField(
                value = inputValue,
                onValueChange = onValueChange,
                singleLine = true,
                textStyle = TextStyle(
                    fontSize = 16.sp,
                    color = colorScheme.onSurface
                ),
                keyboardOptions = KeyboardOptions.Default.copy(
                    keyboardType = KeyboardType.Number,
                    imeAction = ImeAction.Done
                ),
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 12.dp) // 调整文本与输入框边缘的内间距
            )
        }
    }
}

